from google.appengine.ext import webapp
#from ft_table import FtTable
from testing import get_request
#import dlz_config as dc
import model, logging, os
from google.appengine.ext.webapp import template
from gae_db_manager import GaeDbManager

def cleanTestLocation(text):
    '''
    replace common errors
    '''
    
    
    replace_list = [('Of', 'of'),
                    ('Cl', 'CL'),
                    ('cl', 'CL'),
                    ('Ft', 'ft')]
    
    return replaceWords(replace_list, text.title())

def replaceWords(replace_list, text):
    '''
    split a sentence into words, and replace words with corrected ones
    '''
    parts = text.split()
    results = []
    for part in parts:
        for (f,r) in replace_list:
            if part==f:
                part = r
            
        results.append(part) 
        
    return ' '.join(results)

def cleanTestInterval(text):
    '''
    common test interval errors
    '''
    replace_list = [('BEG', 'Below Existing Grade'),
                    ('beg', 'Below Existing Grade'),
                    ('AB', 'Aggregate Base'),
                    ('ab', 'Aggregate Base'),
                    ('S/G', 'Subgrade'),
                    ('SG', 'Subgrade'),
                    ('sg', 'Subgrade'),
                    ('s/g', 'Subgrade')]
    return replaceWords(replace_list, text).title()

def processCompaction(records):
    return process_records(records, 'compaction_test')

def processAsphalt(records):
    return process_records(records, 'asphalt_test')

def download_whole_table(tbl):
    gdm = GaeDbManager(tbl)
    return gdm.query({'where':'', 'sort':'', 'dir':'', 'limit':'', 'start':''}, 'csv')


def download_schema():
    q = model.dlz_table_schema.all()
    import csv, StringIO
    out = StringIO.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    header = model.dlz_table_schema.fields().keys()
    writer.writerow(['google_key'] + header)
    for r in q:
        row = [str(r.key())]
        for fld in header:
            row.append(getattr(r, fld))
        writer.writerow(row)
    results = out.getvalue()
    out.close()
    return results

def process_records(records, table_name):
    q = model.dlz_table_schema.all().filter('table_name = ', table_name).filter('exportable = ', 'YES').order('field_position')
    row1 = []
    row2 = []
    for r in q:
        row1.append(r.field_name)
        row2.append(r.field_label)
    row1.append('google_key')
    row2.append('google_key')
    import csv, StringIO
    out = StringIO.StringIO()
    writer = csv.writer(out, lineterminator='\n')
    writer.writerow(row1)
    writer.writerow(row2)
    for record in records:
        logging.info(record)
        row = []
        for fld in row1:
            value = record.get(fld)
            if fld=='test_location':
                value = cleanTestLocation(value)
            if fld=='test_interval':
                value = cleanTestInterval(value)
            if fld=='project_number':
                value = "'%s" % value 
            row.append(value)
        
        writer.writerow(row)
         
    results = out.getvalue()
    out.close()
    return results

class DownloadHandler(webapp.RequestHandler):

    def get(self):
        self.post()
#        format = self.request.get('format')
#        if format:
#            self.post()
#        else:
#            path = os.path.join(os.path.dirname(__file__), 'template/download.html')
#            options = 'asphalt_test compaction_test table_schema Email dlz_project_list dlz_connection'.split()
#            self.response.out.write(template.render(path, {'options': options}))
    def post(self):
        request = get_request(self.request, where_clause = [])        
        format = self.request.get('format')
        #download in csv format, ignore the start and limit
        request['start'] = ''
        request['limit'] = ''
        table_name = self.request.get('table_name')
        if table_name=='table_schema':
            csv_text = download_schema()
            fname = 'table_schema.csv'
        else:
            gdm = GaeDbManager(table_name)
            if format=='whole'=='whole':
                csv_text = gdm.query(request, 'csv')
            else:
                csv_text = gdm.query(request, 'csvfiltered')
            fname = '%s.csv' % table_name

        self.response.headers["Content-Type"] = "application/octet-stream"
        self.response.headers["Content-Disposition"] = "attachment;Filename=%s" % fname  
        self.response.headers["Cache-Control"] = "no-store, no-cache, no-transform, must-revalidate, private"
        self.response.out.write(csv_text)
